<template>
	<view class="pd10_15">
		<view class="pd10_15" @tap="showinfo()">{{$t('score.buytip')}}</view>
		<view class="flex wrap space ">
			<view v-for="(item,index) in moneyList" :key="index" :class="selid==item.id?'selected':''"
				class="box pd20_15 item" @tap="changeNum(index)">
				<view class="ft14 num">{{item.num}} {{$t('Score')}}</view>
				<view class="ft12 price"><text class="ft24">{{item.price}}</text>{{item.currency}}</view>
				<view class="ft12 text">{{$t('Recharge tip')}}</view>
			</view>
		</view>
		<view class="box mt16 pd16_15">
			<view class="ft16 pb16 ftw600 cl-main">{{$t('Payment')}}</view>
			<radio-group @change="changeType">
				<block v-for="(item,index) in payTypes" :key="index">
					<view v-if="item.open==1" class="pt16 pb16 flex alcenter space bdtop">
						<view class="flex alcenter">
							<text class="iconfont iconicon_arrow_circle ft20" style="color: #55aaff;"></text>
							<text class="ml15 ft14 ftw500 cl-main">{{item.title}}</text>
						</view>
						<view>
							<radio :value="item.name" :checked="payType == item.name" :disabled="false"
								:color="tempColor" />
						</view>
					</view>
				</block>
			</radio-group>
		</view>
		<view style="margin-bottom: 150rpx;"></view>
		<view class="form-footer-h form-footer">
			<view class="form-footer-main pd10_15 flex">
				<button @click="paykami" class="btn-big">{{$t('Cryptocard')}}</button>
				<button @click="paySuccess" :style="getBtnStyle" :loading="loading"
					class="btn-big">{{$t('Pay Now')}}</button>
			</view>
		</view>
		<pop ref="infopop" direction="center" :is_close="true" :is_mask="true" :width="90" height="fit-content"
			:maskFun="false">
			<scroll-view class="mt16 box" scroll-y="true" style="height:800rpx;">
				<view class="pd10_15">
					<rich-text :nodes="tiptext"></rich-text>
				</view>
			</scroll-view>
		</pop>
		<hFormAlert v-if="cancelShow" :title="this.$t('Cryptocard')" name="cancel_desc"
			:placeholder="this.$t('Please enter the card number')" @confirm="confirm" @cancel="cancel"
			:confirmText="this.$t('OK')" :cancelText="this.$t('Cancel')"></hFormAlert>
	</view>
</template>

<script>
	import {
		Iap,
		IapTransactionState
	} from "@/common/iap.js"
	import hFormAlert from '@/components/h-form-alert/h-form-alert.vue';
	import pop from "@/components/ming-pop/ming-pop.vue";
import { log } from "video.js";
	let timer = null;
	export default {
		components: {
			hFormAlert,
			pop
		},
		data() {
			return {
				selid: 0,
				moneyList: [],
				goodsPrice: 0,
				openid: '',
				userinfo: '',
				cancelShow: false,
				payid: 0,
				tiptext: '',
				loading: false,
				productId: "", //苹果内购产品id
				products: [], //充值所有的虚拟id
				productList: [],
				payTypes: [],
				payType: '',
				useiap: false, //是否使用苹果内购
				currency: 'USD',
				drama_id: 0,
				video_id: 0
			}
		},
		onLoad(e) {
			//视频来源
			if (e.vid) {
				this.drama_id = e.vid
			}
			if (e.mid) {
				this.video_id = e.mid
			}
			this.getproduct()
			this.artinfo()
			this.payid = uni.getStorageSync("payid")
			if (this.payid > 0) {
				timer = setInterval(() => {
					this.checkpay(this.payid)
				}, 1000);
			}

			// // //判断支付方式开始
			// let payTypes = uni.getStorageSync("config").paytypes;
			// // #ifdef H5
			// //公众号里不能用支付宝
			// var ua = window.navigator.userAgent.toLowerCase();
			// if (ua.match(/MicroMessenger/i) == 'micromessenger') {
			// 	for (var i = 0; i < payTypes.length; i++) {
			// 		if (payTypes[i].name == 'alipay') {
			// 			payTypes[i].open = 0;
			// 		}
			// 	}
			// }
			// // #endif
			// this.payTypes = payTypes;
			// for (var i = 0; i < payTypes.length; i++) {
			// 	if (payTypes[i].open == 1) {
			// 		this.payType = payTypes[i].name
			// 		break;
			// 	}
			// }
			 this.$httpas.post('/api/pay/payType',{}).then(response => {
				let [err,res] = response
				let data = res.data
				if (data.code == 1) {
					this.payTypes = data.data.map(t => ({title:t.name,name:t.type.toString(),open:1}))
					this.payType = this.payTypes[0].name
				}
			})
		},
		onShow() {
			uni.setNavigationBarTitle({
				title: this.$t('Integral recharge')
			});
		},
		methods: {
			async artinfo() {
				let data = {
					type: 'recharge'
				};
				let [err, res] = await this.$httpas.get('/api/index/artinfo', data);
				if (res.data.code == 1) {
					this.tiptext = res.data.data.content
				}
			},
			showinfo() {
				this.$refs.infopop.show();
			},
			async getproduct() {
				let data = {};
				data.token = uni.getStorageSync("userinfo").token;
				data.uid = uni.getStorageSync("userinfo").id;
				let [err, res] = await this.$httpas.get('/api/user/score_group', data);
				if (res.data.code == 1) {
					this.moneyList = res.data.data
					//虚拟支付产品列表
					for (var i = 0; i < this.moneyList.length; i++) {
						this.products.push(this.moneyList[i].vpid)
					}
					this.changeNum(0)
					// #ifdef APP-PLUS
					//苹果内支付
					if (uni.getSystemInfoSync().osName == "ios" && this.useiap == true) {
						this._iap = new Iap({
							products: this.products // 苹果开发者中心创建
						})
						this.init();
					}
					// #endif
				}
			},
			changeNum(index) {
				let selid = this.moneyList[index].id
				let vpid = this.moneyList[index].vpid
				let price = this.moneyList[index].price

				this.selid = parseInt(selid);
				this.productId = vpid;
				this.goodsPrice = price * 100
				this.currency = this.moneyList[index].currency
			},
			paykami() {
				this.cancelShow = true
			},
			cancel() {
				this.cancelShow = false
			},
			async confirm(e) {
				if (!e.kamiNo) {
					this.cancelShow = false
					uni.showToast({
						title: this.$t('Please enter the card number'),
						icon: "none"
					});
					return false
				}
				let data = {};
				data.token = uni.getStorageSync("userinfo").token;
				data.uid = uni.getStorageSync("userinfo").id;
				data.kamiNo = e.kamiNo;
				
				let [err, res] = await this.$httpas.post('/api/user/kami', data);
				if (res.data.code == 1) {
					uni.showModal({
						title: this.$t('Warning'),
						content: this.$t('Pay success'),
						showCancel: false,
						confirmText: this.$t('OK'),
						success: function(res) {
							if (res.confirm) {
								uni.navigateBack();
							}
						}
					});
				} else {
					uni.showToast({
						title: res.data.msg,
						icon: "none"
					});
				}
				this.cancelShow = false
			},
			changeType(e) {
				this.payType = e.detail.value;
			},
			paySuccess() {
				if (this.moneyList.length == 0 || this.payTypes.length == 0) {
					uni.showModal({
						title: this.$t('Warning'),
						content: this.$t('Operation failed'),
						showCancel: false
					});
					return false;
				}
				// //#ifdef H5
				// this.payH5()
				// //#endif
				this.payH5()
				// #ifdef APP-PLUS
				// if (uni.getSystemInfoSync().osName == "ios" && this.useiap == true) {
				// 	this.payapple()
				// } else {
				// 	if (this.payType == 'wxpay') {
				// 		uni.showModal({
				// 			title: this.$t('Warning'),
				// 			content: this.$t('Operation failed'),
				// 			showCancel: false
				// 		});
				// 		return false;
				// 	} else {
				// 		this.payH5()
				// 	}
				// }
				//#endif
			},
			//h5和APP选择支付
			async payH5() {
				if (!this.selid) {
					uni.showToast({
						title: this.$t('Please select a recharge product'),
						icon: "none"
					});
					return false
				}
				uni.showLoading({
					title: 'Loading'
				});

				let data = {};
				data.token = uni.getStorageSync("userinfo").token;
				data.uid = uni.getStorageSync("userinfo").id;
				data.id = this.selid;
				data.actype = 'score'
				data.paytype = this.payType;
				data.platform = 'h5'
				data.currency = this.currency
				data.drama_id = this.drama_id
				data.video_id = this.video_id
				data.paytype = this.payType
				// #ifdef H5
				var ua = window.navigator.userAgent.toLowerCase();
				if (ua.match(/MicroMessenger/i) == 'micromessenger') {
					data.platform = 'wxgzh';
				}
				// #endif
				let [err, res] = await this.$httpas.post('/api/pay/recharge', data);
				if (res.data.code == 1) {
					uni.hideLoading();
					console.log('recharge',res.data.data);
					// #ifdef APP-PLUS  
					uni.navigateTo({
						url: '/pages/client/webva?url=' + res.data.data.url
					})
					// #endif  
					// #ifdef H5
					window.location.href = res.data.data.url
					// #endif
					//监控支付
					if (data.platform == 'wxgzh') {
						uni.setStorageSync('payid', res.data.data.payid);
					}
				} else {
					uni.hideLoading();
					uni.showToast({
						title: res.data.msg,
						icon: "none"
					});
				}
			},
			checkpay(payid) {
				let data = {
					'payid': payid
				};
				data.token = uni.getStorageSync("userinfo").token;
				data.uid = uni.getStorageSync("userinfo").id;
				uni.request({
					url: this.configs.webUrl + '/api/pay/checkpay',
					data: data,
					success: res => {
						if (res.data.code == 1) {
							if (res.data.data == 2) {
								if (timer) {
									clearInterval(timer);
								}
								uni.removeStorageSync('payid');
								uni.switchTab({
									url: '/pages/client/member/index'
								});
							}
						}
					}
				});
			},
			async init() { //初始化苹果内支付
				uni.showLoading({
					title: this.$t('Loading')
				});

				try {
					// 初始化，获取iap支付通道
					await this._iap.init();

					// 从苹果服务器获取产品列表
					this.productList = await this._iap.getProduct();
					this.productId = this.productList[0].productid;
					//console.log(this.productList)
				} catch (e) {
					uni.showModal({
						title: this.$t('Warning'),
						content: this.$t('Pay failed'),
						showCancel: false
					});
				} finally {
					uni.hideLoading();
				}

				if (this._iap._ready) {
					this.restore();
				}
			},
			async restore() {
				// 检查上次用户已支付且未关闭的订单，可能出现原因：首次绑卡，网络中断等异常
				try {
					// 从苹果服务器检查未关闭的订单，可选根据 username 过滤，和调用支付时透传的值一致
					const transactions = await this._iap.restoreCompletedTransactions({
						username: ""
					});
					if (!transactions.length) {
						return;
					}
					for (let i = 0; i < transactions.length; i++) {
						let transaction = transactions[i]
						//console.log(transaction)
						switch (transaction.transactionState) {
							case IapTransactionState.purchased:
								// 用户已付款，在此处请求开发者服务器，在服务器端请求苹果服务器验证票据
								let result = await this.validatePaymentResult({
									orderId: transaction.payment.username,
									transactionReceipt: transaction.transactionReceipt, // 不可作为订单唯一标识
									transactionIdentifier: transaction.transactionIdentifier
								});
								// 验证通过，交易结束，关闭订单
								if (result) {
									await this._iap.finishTransaction(transaction);
								}
								break;
							case IapTransactionState.failed:
								// 关闭未支付的订单
								await this._iap.finishTransaction(transaction);
								break;
							default:
								break;
						}
					}
				} catch (e) {
					uni.showModal({
						content: e.message,
						showCancel: false
					});
				}
			},
			async payapple() {
				if (this.loading == true) {
					return;
				}
				this.loading = true;

				uni.showLoading({
					title: this.$t('Loading')
				});

				try {
					// 从开发者服务器创建订单
					const orderId = await this.createOrder();

					// 请求苹果支付
					const transaction = await this._iap.requestPayment({
						productid: this.productId,
						manualFinishTransaction: true,
						username: orderId //根据业务需求透传参数，关联用户和订单关系
					});
					//console.log(transaction)
					// 在此处请求开发者服务器，在服务器端请求苹果服务器验证票据
					let result = await this.validatePaymentResult({
						orderId: orderId,
						transactionReceipt: transaction.transactionReceipt, // 不可作为订单唯一标识
						transactionIdentifier: transaction.transactionIdentifier
					});

					// 验证成功后关闭订单
					if (result) {
						await this._iap.finishTransaction(transaction);
					}
					// 支付成功
					uni.showModal({
						title: this.$t('Warning'),
						content: this.$t('Pay success'),
						showCancel: false,
						confirmText: this.$t('OK'),
						success: function(res) {
							if (res.confirm) {
								uni.navigateBack();
							}
						}
					});
				} catch (e) {
					uni.showModal({
						content: this.$t('Pay failed'),
						showCancel: false
					});
				} finally {
					this.loading = false;
					uni.hideLoading();
				}
			},
			createOrder() { //创建苹果内购订单
				return new Promise((resolve, reject) => {
					let data = {};
					data.token = uni.getStorageSync("userinfo").token;
					data.uid = uni.getStorageSync("userinfo").id;
					data.id = this.selid;
					data.actype = 'score'
					data.paytype = 'appleiap'
					data.currency = this.currency
					data.drama_id = this.drama_id
					data.video_id = this.video_id
					uni.request({
						url: this.configs.webUrl + '/api/pay/recharge',
						data: data,
						header: {
							'site': this.configs.subsite
						},
						success: res => {
							if (res.data.code == 1) {
								resolve(res.data.data.out_trade_no)
							} else {
								reject(res.data.msg)
							}
						}
					});
				})
			},
			validatePaymentResult(data) { //验证苹果内购订单
				return new Promise((resolve, reject) => {
					uni.request({
						url: this.configs.webUrl + '/index/pay/notify_iap',
						data: data,
						success: res => {
							if (res) {
								resolve(1)
							} else {
								reject(0)
							}
						}
					});
				});
			}
		}
	}
</script>

<style>
	.item {
		width: 300rpx;
		text-align: center;
		margin: 20rpx;
		border: solid 1px #cccccc;
	}

	.selected {
		background-color: bisque;
		border: solid 1px orange;
	}

	.item .num {
		margin: 30rpx 0;
	}

	.item .price {
		color: orange;
		margin: 30rpx 0;
	}

	.item .text {
		color: #999999;
	}

	.bdtop {
		border-top: solid 1px #eeeeee;
	}
</style>